/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.android.music.download;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.net.NetworkInfo.State;
import android.text.TextUtils;

public class HttpURLdownloader {

    public static final String lrcPrefixUrl = "http://lrc.ttpod.com/q?title=%s&artist=%s&mediatype=%s&duration=%d&bitrate=%d&srate=%d&raw=%d&%s";

    private static final String USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB6 (.NET CLR 3.5.30729)";

    private static final int CONN_TIME_OUT = 20 * 1000;

    private static final int READ_TIME_OUT = 20 * 1000;

    private static final int BUFFER_SIZE = 8192;

    public String getTheStream(Context mContext, String utl) {
        if (isNetworkConnected(mContext)) {
        }
        HttpClient httpClient = createHttpClient(mContext);
        try {
            // 创建 HttpGet 方法，该方法会自动处理 URL 地址的重定向
            HttpGet httpGet = new HttpGet(utl);
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                // 错误处理，例如可以在该请求正常结束前将其中断
                httpGet.abort();
                return null;
            } else {
                // 读取更多信息
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, getDefaultCharset());
                // 返回结果 去掉<em></em>
                String rem = result.replace("&lt;em&gt;", " ");
                String rme = rem.replace("&lt;/em&gt;", " ");
                return rme;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }

    public String getDefaultCharset() {
        return "utf8";
    }

    /**
     * 判断是否链接网络
     * 
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        NetworkInfo networkInfo = getActiveNetworkInfo(context);
        return networkInfo != null && networkInfo.isConnected();
    }

    private static NetworkInfo getActiveNetworkInfo(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return null;
        }
        return connectivity.getActiveNetworkInfo();
    }

    public static HttpClient createHttpClient(Context context) {

        // 创建 HttpParams 以用来设置 HTTP 参数（这一部分不是必需的）
        HttpParams httpParams = new BasicHttpParams();

        // 设置连接超时和 Socket 超时，以及 Socket 缓存大小
        HttpConnectionParams.setConnectionTimeout(httpParams, CONN_TIME_OUT);
        HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT);
        HttpConnectionParams.setSocketBufferSize(httpParams, BUFFER_SIZE);

        // 设置重定向，缺省为 true
        HttpClientParams.setRedirecting(httpParams, true);

        // 检测代理设置
        String proxyHost = Proxy.getHost(context);
        int proxyPort = Proxy.getPort(context);

        boolean isWifiConnected = isWifiConnected(context);
        // boolean isMobileConnected = isMobileConnected(context);

        if (!isWifiConnected && !TextUtils.isEmpty(proxyHost)) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }

        // 设置 user agent
        String userAgent = USER_AGENT;
        HttpProtocolParams.setUserAgent(httpParams, userAgent);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }

    public static boolean isWifiConnected(Context context) {
        return getNetworkState(context, ConnectivityManager.TYPE_WIFI) == State.CONNECTED;
    }

    public static boolean isMobileConnected(Context context) {
        return getNetworkState(context, ConnectivityManager.TYPE_MOBILE) == State.CONNECTED;
    }

    private static State getNetworkState(Context context, int networkType) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getNetworkInfo(networkType);
        return info == null ? null : info.getState();
    }

}
